﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace GTA.ExceptionHandling
{
    public sealed class ValidationException : BaseException
    {
        #region Properties
        private List<ValidationField> ValidationErrors;
        public override String Message
        {
            get
            {
                return GetDetailedErrorMessage();
            }
        }
        public override string MessageFull
        {
            get
            {
                return GetFullException();
            }
        }
        #endregion

        #region Constructors
        public ValidationException(Int32 ErrorNumber)
            : base(ErrorNumber)
        {
        }
        public ValidationException(String ErrorMessage)
            : this(ErrorMessage, null)
        {
        }
        public ValidationException(String ErrorMessage, List<ValidationField> fields)
            : base(ErrorMessage)
        {
            this.ValidationErrors = fields;
        }
        #endregion

        #region Methods
        public void AddValidationError(ValidationField field)
        {
            if (this.ValidationErrors == null)
                this.ValidationErrors = new List<ValidationField>();
            this.ValidationErrors.Add(field);
        }
        private string GetDetailedErrorMessage()
        {
            StringBuilder message = new StringBuilder();
            message.Append(base.ErrorMessage);

            if (ValidationErrors != null && ValidationErrors.Count > 0)
            {
                message.Append("\r\n");
                foreach (ValidationField itemField in ValidationErrors)
                {
                    if (!String.IsNullOrEmpty(itemField.FieldName))
                    {
                        message.Append("Campo: ");
                        message.Append(itemField.FieldName);
                        message.Append("\r\n");
                    }
                    if (!String.IsNullOrEmpty(itemField.OriginalValue))
                    {
                        message.Append("Valor Original: ");
                        message.Append(itemField.OriginalValue);
                        message.Append("\r\n");
                    }
                    if (itemField.AllowedValues != null && itemField.AllowedValues.Count > 0)
                    {
                        message.Append("Valores Permitidos: ");
                        message.Append("\r\n");
                        itemField.AllowedValues.ForEach(it => message.Append("\t" + it + "\r\n"));
                    }
                }
            }

            return message.ToString();
        }
        #endregion
    }
}
